/*
 * Copyright 2002-2016 the atnoce.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.onepass.core;

import com.atnoce.onepass.dao.DirTypeDao;
import com.atnoce.onepass.dao.OnepassConfigDao;
import com.atnoce.onepass.dao.PasswordItemDao;
import com.atnoce.onepass.net.BasicNetService;
import com.atnoce.onepass.utils.*;
import com.atnoce.onepass.view.IndexLayoutController;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
import tray.animations.AnimationType;
import tray.notification.NotificationType;
import tray.notification.TrayNotification;

import java.util.Map;

/**
 * @author atnoce.com
 * @date 2016/11/8
 * @since 1.0.0
 */
public class BackService {
    private BackService(){

    }
    private static BackService backService;
    private static long time=1476960799526l;

    public static void updateClock(){
        time = System.currentTimeMillis();
    }

    /**
     * 启动自动锁定服务
     * @param btn
     */
    public static void startClockService(Button btn){
        time = System.currentTimeMillis();

        Service<String> service=new Service<String>() {
            @Override
            protected Task<String> createTask() {
                return new Task<String>() {
                    @Override
                    protected String call() throws Exception {
                        long currentTimeMillis = System.currentTimeMillis();
                        while((currentTimeMillis-time)/1000/60<Long.parseLong(Cache.getOc().getKongXianLockTime())){
                            currentTimeMillis = System.currentTimeMillis();
                            Thread.sleep(1000);
                        }
                        return "end";
                    }
                };
            }
        };
        service.setOnSucceeded((WorkerStateEvent event) -> {
            btn.fire();
        });

        service.start();
    }

    /**
     * 启动数据同步服务
     */
    public static void startSyncService(IndexLayoutController indexLayoutController,ImageView coludImage,String coludAccount){
        Service<String> service=new Service<String>() {
            @Override
            protected Task<String> createTask() {
                return new Task<String>() {
                    @Override
                    protected String call() throws Exception {
                        //执行同步代码
                        BasicNetService.getInstance().exeSynch(coludAccount);

                        return "end";
                    }
                };
            }
        };
        if (coludImage!=null){
            service.setOnFailed((WorkerStateEvent event)->{
                //coludImage.setImage(new Image(BackService.class.getResourceAsStream("../view/image/colud_change.png")));
                TrayNotification tray=new TrayNotification();
                tray.setTitle("同步提示");
                tray.setMessage("同步发生问题："+event.getSource().getException().getMessage());
                tray.setNotificationType(NotificationType.ERROR);
                tray.setAnimationType(AnimationType.FADE);//设置通知弹出的效果
                tray.showAndDismiss(Duration.seconds(10));//3秒后自动消失

            });
            service.setOnSucceeded((WorkerStateEvent event) -> {
                if (indexLayoutController!=null)
                indexLayoutController.initLeftList();//刷新列表
                //coludImage.setImage(new Image(BackService.class.getResourceAsStream("../view/image/cloud_24_24_success.png")));
                TrayNotification tray=new TrayNotification();
                tray.setTitle("同步提示");
                tray.setMessage("密码库同步已经完成，数据与服务器保持一致！");
                tray.setNotificationType(NotificationType.SUCCESS);
                tray.setAnimationType(AnimationType.FADE);//设置通知弹出的效果
                tray.showAndDismiss(Duration.seconds(3));//3秒后自动消失
            });
            service.setOnRunning((WorkerStateEvent event)->{
                //coludImage.setImage(new Image(BackService.class.getResourceAsStream("../view/image/5-121204193R6.gif")));
            });
        }
        service.start();
    }
    public static void startUpdateModifyTimeService(){
        if (Cache.updateTimeServiceRun){
            return;
        }
        Map<QueueType,String> queueTypeStringMap;
        Service<String> service=new Service<String>() {
            @Override
            protected Task<String> createTask() {

                return new Task<String>() {
                    @Override
                    protected String call() throws Exception {
                        boolean flag=true;
                        while (flag){
                            Map<QueueType, String> updateModifyTimeQueue = Cache.getUpdateModifyTimeQueue();
                            if (updateModifyTimeQueue!=null){
                                try{
                                    for (QueueType type:updateModifyTimeQueue.keySet()){
                                        String time=CommonUtil.getTime();
                                        //如果开启了云服务，则从授时服务器获取时间
                                        if (Boolean.valueOf(Cache.getProConfig(Const.ACTIONCLOUD))){
                                            time=BasicNetService.getTime()+"";
                                        }
                                        switch (type){
                                            case CONFIG:
                                                new OnepassConfigDao().updateModifyTime(time);
                                                break;
                                            case DIRCLASS:
                                                new DirTypeDao().updateModifyTime(updateModifyTimeQueue.get(type),time);
                                                break;
                                            case PASSITEM:
                                                new PasswordItemDao().updateModifyTime(updateModifyTimeQueue.get(type),time);
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                }catch (Exception e){
                                    //未更新成功，将任务放回队列
                                    Cache.addUpdateModifyTimeQueue(updateModifyTimeQueue);
                                    e.printStackTrace();
                                }
                            }else{
                                flag=false;
                            }
                        }
                        return "end";
                    }
                };
            }
        };
        service.setOnRunning((WorkerStateEvent event)->{
            Cache.updateTimeServiceRun=true;
        });
        service.setOnSucceeded((WorkerStateEvent event)->{
            //启动同步
            try {
                if (Boolean.valueOf(Cache.getProConfig(Const.ACTIONCLOUD))){
                    startSyncService(null,null,SecurityController.getSecurityInstence().decryptColudAccount(Cache.getProConfig(Const.COLUDACCOUNT),Cache.getKey()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Cache.updateTimeServiceRun=false;
        });
        service.setOnFailed((WorkerStateEvent event)->{
            Cache.updateTimeServiceRun=false;
        });
        service.start();
    }
}
